﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Wildweeds.SSO.UserManager;
using Wildweeds.SSO.Entity;
using Wildweeds.SSO.Common;

namespace Wildweeds.SSO.Passport
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var userInfo = Session["user"] as UserInfo;
            
            //用户已登录
            if (userInfo != null)
            {
                Logined(userInfo);
            }
        }

        protected void UserLogin(object sender, EventArgs e)
        {
            string userName = txt_userName.Value.Trim();
            string password = txt_password.Value.Trim();

            var userInfo = UserManager.UserManager.GetByUserName(userName);

            string errorMsg = "用户不存在";
            if (userInfo != null)
            {
                if (userInfo.Password != password)
                {
                    errorMsg = "密码错误";
                }
                else
                    errorMsg = string.Empty;
            }
            if (errorMsg.Length > 0)
            {
                Response.Write(errorMsg);
                return;
            }
            else
            {
                Logined(userInfo);
            }
        }

        /// <summary>
        /// 用户已登录
        /// </summary>
        /// <param name="userInfo"></param>
        void Logined(UserInfo userInfo)
        {
            string returnUrl = Context.Request.QueryString["ReturnUrl"];

            if (string.IsNullOrWhiteSpace(returnUrl))
            {
                //本页面登录
                Response.Redirect("/");
                return;
            }

            string splitStr = returnUrl.Contains("?") ? "&" : "?";
            string returnFormat = "{0}{1}token={2}";
            string tokenStr = string.Empty;

            TokenInfo token = new TokenInfo()
            {
                tokenId = Guid.NewGuid(),
                IsValid = true,
                CreateTime = DateTime.Now,
                UserName = userInfo.UserName,
                RemoteIp = Utility.RemoteIp
            };
            bool addTokenResult = TokenManager.AddToken(token);
            if (addTokenResult)
            {
                tokenStr = token.tokenId.ToString();
                //添加到Session中
                Session["User"] = userInfo;
            }
            else
            {
                Response.Write("Token添加失败");
            }
            Response.Redirect(string.Format(returnFormat, returnUrl, splitStr, tokenStr));   
        }
    }
}